const {
  HomeWorkModel,
  classModel,
  StuModel,
  StudentWorkModel,
  FileModel,
  UploadModel,
} = require("../model");
const {
  createFolder,
  uploadFile,
  deleteFile,
  deleteFolder,
} = require("./fileContorller");
// 排序函数
function sortByStudentNum(works) {
  return works.sort((a, b) => {
    // 使用字符串比较，因为stuNum是字符串类型
    return a.studentId.stuNum.localeCompare(b.studentId.stuNum);
  });
}
//创建作业
exports.createWork = async (req, res) => {
  let { name, parentId, classId } = req.body;
  if (!name || !parentId || !classId) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "参数不全",
    });
  }
  let createUser = req.user.stuName ? req.user.stuName : req.user.teaName;
  if (!createUser) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "账号名称异常，请重新登录",
    });
  }
  let if1 = await HomeWorkModel.findOne({ name, parentId, classId });
  if (if1) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "作业已存在",
    });
  }
  let if2 = await HomeWorkModel.findOne({ name, parentId });
  let if3 = await FileModel.findOne({ name, parentId });
  if (if2 || if3) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "文件存在重复命名",
    });
  }
  try {
    const classInfo = await classModel.findById(classId);
    if (!classInfo) {
      throw new Error("Class not found"); // 如果没有找到班级，抛出错误
    }
    // 假设StuModel和StudentWorkModel已经定义
    const stulist = await StuModel.find({ className: classInfo.className });
    //将对应数据添加到作业模型
    const work = new HomeWorkModel({
      name,
      parentId,
      classId,
      createUser,
      shouldNumber: stulist.length, // 应交人数
      hadNumber: 0, // 已交人数
    });

    // 假设createFolder函数已经定义，并且如果需要，它应该在这里被调用
    // await createFolder(req); // 如果createFolder是异步的并且需要在这里调用

    // 班级作业数量+1
    classInfo.count += 1;
    await classInfo.save();

    await work.save();

    const workId = work._id;
    const stuIds = stulist.map((item) => item._id);
    // 批量插入学生作业以提高性能
    const stuWorks = stuIds.map((studentId) => ({
      studentId,
      workId,
    }));
    await StudentWorkModel.insertMany(stuWorks);

    //创建文件夹
    await createFolder(req, res);
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "创建失败" + error.message,
    });
  }
};
//获取作业列表
exports.getWorkList = async (req, res) => {
  const { pageNo = 1, pageSize = 10 } = req.query;
  try {
    let result = await HomeWorkModel.find()
      .skip((pageNo - 1) * pageSize)
      .limit(pageSize)
      .sort({ CreateAt: -1 })
      .populate("classId", "className");

    for (let i = 0; i < result.length; i++) {
      let curr = await FileModel.findOne({
        parentId: result[i].parentId,
        name: result[i].name,
      });
      result[i]._doc.currentId = curr._id;
    }
    let total = await HomeWorkModel.countDocuments();
    return res.status(200).json({
      code: 200,
      data: {
        list: result,
        total,
      },
      message: "获取成功",
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "获取失败" + error.message,
    });
  }
};
//获取作业详情
exports.getWorkDetail = async (req, res) => {
  const { workId } = req.query;
  if (!workId) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "参数错误",
    });
  }
  try {
    let workInfo = await StudentWorkModel.find({ workId: workId }).populate(
      "studentId",
      "stuName stuNum"
    );
    if (!workInfo) {
      return res.status(404).json({
        code: 404,
        data: null,
        message: "作业不存在",
      });
    }
    return res.status(200).json({
      code: 200,
      data: sortByStudentNum(workInfo),
      message: "获取成功",
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "获取失败" + error.message,
    });
  }
};
//学生提交作业
exports.uploadWork = async (req, res) => {
  const { parentId, workId } = req.query;
  if (!parentId || !workId) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "参数错误",
    });
  }
  if (!req.user.stuName) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "非学生用户无法提交作业",
    });
  }
  //判断文件是否存在
  if (!req.file) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "文件不存在",
    });
  }

  try {
    //判断是否在提交班级内
    let result1 = await StudentWorkModel.findOne({
      studentId: req.user._id,
      workId: workId,
    });
    //未在提交名单内
    if (!result1) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "未在提交名单内",
      });
    }
    //如果已经提交过，则返回错误信息
    if (result1.state == 1) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "已提交过,请勿重复提交",
      });
    }
    let iscf = await UploadModel.findOne({
      parentId: parentId,
      fileName: req.file.originalname,
    });
    if (iscf) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "文件名称重复",
      });
    }
    //修改学生作业状态
    result1.state = 1;
    result1.UpdateAt = Date.now();
    //修改学生作业提交次数
    let result2 = await StuModel.findOne({ _id: req.user._id });
    result2.submitNum += 1;
    //修改对应作业提交次数
    let result3 = await HomeWorkModel.findOne({ _id: workId });
    result3.hadNumber += 1;
    await result1.save();
    await result2.save();
    await result3.save();
    req.work = result1;
    await uploadFile(req, res);
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "提交失败" + error.message,
    });
  }
};
//删除学生作业
exports.deleteWork = async (req, res) => {
  const { workId } = req.query;
  if (!workId) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "参数错误",
    });
  }
  try {
    let result = await StudentWorkModel.findOne({ _id: workId }).populate(
      "studentId"
    );
    if (!result) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "未找到该学生",
      });
    }
    result.state = 0;
    let result1 = await StuModel.findOne({ _id: result.studentId });
    result1.submitNum -= 1;
    let result2 = await HomeWorkModel.findOne({ _id: result.workId });
    result2.hadNumber -= 1;
    await result.save();
    await result1.save();
    await result2.save();
    if (!result.fileId) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "你还没有提交作业",
      });
    }
    req.query.id = result.fileId;
    req.query.fileId = result.fileId;
    await deleteFile(req, res);
  } catch (error) {}
};
//删除作业
exports.deleteHomWork = async (req, res) => {
  const { parentId, password } = req.body;
  if (!parentId || !password) {
    return res.status(400).json({
      code: 400,
      data: null,
      message: "参数错误",
    });
  }
  if (req.user.teaPassword) {
    if (password != req.user.teaPassword) {
      return res.status(400).json({
        code: 400,
        message: "密码错误",
        data: null,
      });
    }
  } else {
    if (password != req.user.password) {
      return res.status(400).json({
        code: 400,
        message: "密码错误",
        data: null,
      });
    }
  }
  try {
    //文件结果
    let result1 = await FileModel.findOne({ _id: parentId });
    if (!result1) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "未找到对应文件",
      });
    }
    let result2 = await HomeWorkModel.findOne({
      parentId: result1.parentId,
      name: result1.name,
    });
    if (!result2) {
      return res.status(400).json({
        code: 400,
        data: null,
        message: "未找到该作业",
      });
    }
    let result3 = await StudentWorkModel.find({ workId: result2._id });
    let result5 = await classModel.findOne({ _id: result2.classId });

    req.query.id = result1._id;
    req.query.fileId = result1._id;
 

    //学生记录中state为1的学生，提交次数减一
    let stateStudents = result3.filter((item) => item.state == 1);
    for (let i = 0; i < stateStudents.length; i++) {
      let result4 = await StuModel.findOne({ _id: stateStudents[i].studentId });
      result4.submitNum -= 1;
      await result4.save();
    }
    //删除对应的学生记录
    await StudentWorkModel.deleteMany({ workId: result2._id });
    //班级记录中作业次数减一

    result5.count -= 1;
    await result5.save();
    //删除作业记录
    await HomeWorkModel.deleteOne({ _id: result2._id });
    await deleteFolder(req, res);
  } catch (error) {
    return res.status(500).json({
      code: 500,
      data: null,
      message: "删除失败" + error.message,
    });
  }
};
